package com.atguigu.oss.service.imp;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImp implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile multipartFile){
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取文件输入流
            InputStream inputStream = multipartFile.getInputStream();

            // 设置文件名,这里用uuid来设置随机文件名,防止文件因为文件名相同而覆盖.
            String fileName = multipartFile.getOriginalFilename();
            //把生成的uuid里面的-去除掉
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid + fileName;

            //按照日期上传时间来分类
            //2021/7/7
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;

            ossClient.putObject(bucketName, fileName, inputStream);

            //返回上传之后的文件url
            //https://edu-guli-45644.oss-cn-beijing.aliyuncs.com/ailun.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        }catch (IOException e){
            e.printStackTrace();
        }
        finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return null;
    }
}
